package com.t2two.example.common.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.KeyPair;

/**
 * @version 1.0
 * @description: TODO
 * @author: lifei
 * @date: 2025/2/17 9:39
 */
@Slf4j
public class SM2Util {

    private static SM2 sm2;
    /**私钥*/
    final private static String privateKey = "3c57e96dac2d6d0dfd92e400ebb609e584b148b755968d898bd25f226aa5b636";//自己调用下面的getSM2Key生成
    /**公钥*/
    final private static String publicKey = "123456";//自己调用下面的getSM2Key生成

    private static synchronized SM2 getSm2() {
        if (sm2 == null) {
//            Environment environment = SpringBeanUtil.getApplicationContext().getEnvironment();
//            String privateKey = environment.getProperty("encrypt.sm2.privateKey");
//            String publicKey = environment.getProperty("encrypt.sm2.publicKey");
            sm2 = SmUtil.sm2(Base64.decodeBase64(privateKey), Base64.decodeBase64(publicKey));
        }
        return sm2;
    }

    /**
     * 公钥加密
     *
     * @param cipherTxt
     * @return
     */
    public static String encrypt(String cipherTxt) {
        if (!org.springframework.util.StringUtils.hasText(cipherTxt)) {
            return cipherTxt;
        }
        String encryptStr = getSm2().encryptBcd(cipherTxt, KeyType.PublicKey);
        return encryptStr;
    }

    /**
     * 私钥解密
     *
     * @param plainTxt
     * @return
     */
    public static String decrypt(String plainTxt) {
        if (!org.springframework.util.StringUtils.hasText(plainTxt)) {
            return plainTxt;
        }
        String decryptStr = StrUtil.utf8Str(getSm2().decryptFromBcd(plainTxt, KeyType.PrivateKey));
        return decryptStr;
    }

    /**
     * 生成一对 C1C2C3 格式的SM2密钥
     *
     * @return 处理结果
     */
    public static void getSM2Key() {
        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        byte[] privateKey = pair.getPrivate().getEncoded();
        byte[] publicKey = pair.getPublic().getEncoded();
        try {
            System.out.println("私钥" + new String(Base64.encodeBase64(privateKey), CharsetUtil.UTF_8));
            System.out.println("公钥" + new String(Base64.encodeBase64(publicKey), CharsetUtil.UTF_8));
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }
    }
}
